package com.los;

import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;

/**
 * @program: java8
 * @description: 集合
 * @author: Yujuan
 * @create: 2018-06-24 13:52
 **/
public class CollectorIntroduce {
    public static void main(String[] args) {
        List<Apple> apples= Arrays.asList(new Apple("green",100),
                new Apple("red",150),new Apple("yellow",120)
        ,new Apple("white",150),new Apple("green",170));
        List<Apple> greenList=apples.stream().filter(apple -> apple.getColor().equals("blue")).collect(Collectors.toList());
        Optional.ofNullable(greenList).ifPresent(System.out::println);

        Optional.ofNullable(groupByNormal(apples)).ifPresent(System.out::println);


        Optional.ofNullable(groupByFunction(apples)).ifPresent(System.out::println);

        Optional.ofNullable(groupByCollector(apples)).ifPresent(System.out::println);


    }

    private static Map<String,List<Apple>> groupByNormal(List<Apple> apples){
        Map<String,List<Apple>> map=new HashMap<>();
        for (Apple a :
                apples) {
            List<Apple> list=map.get(a.getColor()) ;
            if (null==list){
                list=new ArrayList<>();
                map.put(a.getColor(),list);
            }
            list.add(a);
        }
        return map;
    }

    private static Map<String,List<Apple>> groupByFunction(List<Apple> apples){
        Map<String,List<Apple>> map=new HashMap<>();
        apples.stream().forEach(apple -> {
           List<Apple> colorList=Optional.ofNullable(map.get(apple.getColor())).orElseGet(()->{
                List<Apple> list=new ArrayList<>();
                map.put(apple.getColor(),list);
                return list;
            });
            colorList.add(apple);
        });
        return map;
    }
    private static Map<String,List<Apple>> groupByCollector(List<Apple> apples){
        return apples.stream().collect(groupingBy(Apple::getColor));
    }

}
